//
//  SQSocket.m
//  SQ_NEW
//
//  Created by 刘明 on 2017/5/11.
//  Copyright © 2017年 刘明. All rights reserved.
//

#import "SQSocket.h"
#define kReadTag 2013
#define kWriteTag 410




@interface SQSocket()<GCDAsyncSocketDelegate,GCDAsyncUdpSocketDelegate>

@property (nonatomic, copy) NSString *sq_host;
@property (nonatomic, assign) uint16_t sq_port;

@property (nonatomic, strong) GCDAsyncSocket *socket;

@end

@implementation SQSocket

singleton_implementation(SQSocket)

- (void)setup{
    
    self.sq_host = S_Sorket_new_Url;
    self.sq_port = S_Sorket_new_Port;
}

#pragma mark - 对外方法
- (void)socketConnect{
    
    NSLog(@"********************连接socket*******************");
    self.offLineStyle = SQSocketOffLineByServer;//连接socket还原
    self.socket = [[GCDAsyncSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
    [self.socket connectToHost:self.sq_host onPort:self.sq_port error:nil];
    
}

- (void)socketDidSendMessage:(NSString *)code{
    
    NSData *data =[code dataUsingEncoding:NSUTF8StringEncoding];
    
    [self.socket writeData:data withTimeout:-1 tag:kWriteTag];
}

- (void)socketDisconnect{
    
    NSLog(@"********************断开socket*******************");
    
    self.offLineStyle = SQSocketOffLineByUser;
    
    [self.socket disconnect];
    
    [self.socket setDelegate:nil];
    
    self.socket = nil;
}


#pragma mark - GCDAsyncSocketDelegate


- (void)socket:(GCDAsyncSocket *)sock didConnectToHost:(NSString *)host port:(uint16_t)port{
    
    [self listenMessageAndCheckPingPong];

}

- (void)socket:(GCDAsyncSocket *)sock didReadData:(NSData *)data withTag:(long)tag;{
    

    [self listenMessageAndCheckPingPong];
    //心跳写在这...
    NSString *msg = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    NSLog(@"%s \n %@",__func__,msg);
    
    if (self.socketRecevieDataBlock) {
        
        self.socketRecevieDataBlock(msg);
    }
}


- (void)socket:(GCDAsyncSocket *)sock didWriteDataWithTag:(long)tag;{
    
    NSLog(@"%s \n %ld",__func__,tag);
    
    [self listenMessageAndCheckPingPong];

}

- (void)socketDidDisconnect:(GCDAsyncSocket *)sock withError:(nullable NSError *)err;{
    
    NSLog(@"%s \n %@",__func__,err);
    //断线重连写在这...
    if (self.offLineStyle == SQSocketOffLineByUser) {
        // 如果由用户断开，不进行重连
        return;
    }else{
        
        [self socketConnect];
    }

}

#pragma mark - private
//用Pingpong机制来看是否有反馈
//监听最新的消息
- (void)listenMessageAndCheckPingPong{
    
    //貌似是分段读数据的方法
    //    [self.socket readDataToData:[GCDAsyncSocket CRLFData] withTimeout:10 maxLength:50000 tag:110];
    
    //监听读数据的代理，只能监听10秒，10秒过后调用代理方法  -1永远监听，不超时，但是只收一次消息，
    //所以每次接受到消息还得调用一次
    [self.socket readDataWithTimeout:-1 tag:kReadTag];
    
    //pingpong设置为15秒，如果15秒内没得到反馈就会自动断开连接
    [self.socket readDataWithTimeout:15 tag:kWriteTag];
}


//字典转为Json字符串
- (NSString *)dictionaryToJson:(NSDictionary *)dic
{
    
    NSError *error = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}




@end
